package com.COMP3111H.project;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class NetworkUtility{
	
	public static boolean isOnline(Activity a) { 
		ConnectivityManager cm = 
		        (ConnectivityManager) a.getSystemService(Context.CONNECTIVITY_SERVICE); 
	    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
	    if (netInfo != null && netInfo.isConnected()) { 
	        return true; 
	    } 
	    return false; 
	} 
	
	public static boolean inputCheck(String a) { 
		if(Pattern.matches("[a-zA-Z0-9!@#$%^&()_+-=.,<>{}:; ]*", a))
		{ 
			return true;
		}
	    return false; 
	}
	
	public static String sendHTTP(List<NameValuePair> params, String uriAPI) {
		Log.v("Bookwarm", uriAPI);
		HttpPost httpRequest = new HttpPost(uriAPI);
		try {

			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);

			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				Log.v("Bookwarm", strResult);
				return strResult;
			} else {
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				Log.v("Bookwarm", strResult);
				Log.v("Bookwarm", "return not 200");
				return "error";
			}
		} catch (ClientProtocolException e) {
			Log.v("Bookwarm", "ClientProtocolException");
		} catch (UnsupportedEncodingException e) {
			Log.v("Bookwarm", "UnsupportedEncodingException");
		} catch (IOException e) {
			Log.v("Bookwarm", "IOException");
		}
		return "error";
	}

}